import json

from fastapi import FastAPI, File, UploadFile
import uvicorn
from starlette.middleware.cors import CORSMiddleware

from com.hy.ResultVo import *
from com.sql.db import session
from sqlalchemy import text
from com.schemas.newsbase import NewsBase
from com.models.news import News
app = FastAPI(title="FastAPI demo", description="FastAPI demo")

# 设置跨域
app.add_middleware(CORSMiddleware,
                   allow_origins=["*", ],
                   allow_credentials=True,
                   allow_methods=["*"],
                   allow_headers=["*"]
                   )


@app.get("/getNews2", name="基于ORM框架的查询", response_model=ResultVoNews)
async def getNews2():
    data = session.query(News).all()
    return ResultVoNews(data=data)


@app.get("/getNews", name="获取news信息")
async def getNews():
    sql = "select * from news"
    data = session.execute(text(sql)).fetchall()
    return ResultVoList(data=data)


@app.get("/index", name="welcome to python ！")
async def index():
    return ResultVoStr(data="welcome to use python ！")


@app.get("/say", name="无参接口")
async def say():
    dict = {"contents": "hello python!"}
    return ResultVoDict(data=dict)


# http://192.168.1.99:5000/get2?name=admin
@app.get("/get", name="get 请求带参")
async def get(name):
    dict = {'name': name}
    return ResultVoDict(data=dict)


# http://192.168.1.99:5000/item/1
@app.get("/item/{id}", name="get 请求带参")
async def get_item(id: int, q: str = None):
    dict = {"item_id": id, 'q': q}
    return ResultVoDict(data=dict)


@app.get("/getList", name="返回list数据")
async def getList():
    dict = {"name": "张三", "age": 10}
    list = []
    for x in range(0, 10):
        list.append(dict)
    return ResultVoList(data=list)


@app.post("/getCoin", name="获取coin数据")
async def getCoin(item: ItemModel):
    list = []
    for x in range(0, 10):
        list.append(item)
    return ResultVoList(data=list)


@app.post("/getCoin2", name="coin2 ")
async def getCoin2(item: dict):
    list = []
    for x in range(0, 10):
        list.append(item)
    dict = {"total": len(list), "list": list}
    return ResultVoDict(data=dict)


@app.post("/uploadFile", name="上传文件")
async def uploadFile(file: bytes = File(...)):
    return ResultVoDict(data={'len': len(file)})


@app.post("/uploadFile2", name="上传文件")
async def uploadFile2(file: UploadFile = File(...)):
    filename = file.filename
    c = await file.read()
    content = c.decode("utf-8")
    return ResultVoDict(data={'name': filename, 'content': content})


# 试着打开 http://127.0.0.1:5000/docs
# 运行  uvicorn main:app --reload
if __name__ == '__main__':
    uvicorn.run('main:app', host='192.168.1.99', port=5000, log_level='info')
